#!/usr/bin/python3 -u
"""This module provides a function for executing of disjunction of analyze
events.
"""

import sys
import os
from argparse import ArgumentParser
import locale
import gettext
from subprocess import Popen

import report
from reportclient import (ask_yes_no_yesforever,
                          ask_yes_no_save_result,
                          RETURN_OK,
                          RETURN_CANCEL_BY_USER,
                          RETURN_FAILURE)

GETTEXT_PROGNAME = "abrt"

_ = gettext.gettext

def handle_event(event_name, problem_dir):
    """Helper function handling a single event

    Keyword arguments:
    envet_name -- a name of handled event
    problem_dir -- a path to problem directory

    Returns True if the handled event was successfully executed; otherwise
    returns False.

    """

    state, ret = report.run_event_on_problem_dir(problem_dir, event_name)

    if ret == 0 and state.children_count == 0:
        print("No actions are found for event '%s'" % event_name)
        return RETURN_FAILURE

    return ret


def run_analyze_smart(problem_dir):
    """Runs analyze_RetraceServer event or analyze_LocalGB event.

    At first runs analyze_RetraceServer. If user dismisses
    analyze_RetraceServer event or if the run fails the analyze_LocalGDB event
    will be run.

    Keyword arguments:
    problem_dir -- a path to problem directory

    Returns True if any of the events was successfully performed; otherwise
    returns False.

    """

    retval = RETURN_CANCEL_BY_USER
    allowed = ask_yes_no_save_result("abrt_analyze_upload_coredump",
                _("Ok to upload core dump? (It may contain sensitive data). "\
                  "If your answer is 'No', a stack trace will be generated locally. "\
                  "(It may download a huge amount of data)."))

    if allowed:
        retval = handle_event("analyze_RetraceServer", problem_dir)

    # temporary helper variables for better readability
    option = "abrt_analyze_smart_ask_perform_local_analysis"
    question = _("Do you want to generate a stack trace locally? "\
                 "(It may download a huge amount of data but reporting "\
                 "can't continue without stack trace).")

    # run local GDB if the retrace event was dismissed
    # or if the retrace event failed and user gave us permission to run local GDB
    #
    # don't change the retval to RETURN_CANCEL_BY_USER if ask_yes_no_yesforever() is False
    # we want to catch errors produced by Retrace Server
    if not allowed or (retval != RETURN_OK and ask_yes_no_yesforever(option, question)):
        retval = handle_event("analyze_LocalGDB", problem_dir)

    return retval


if __name__ == "__main__":
    try:
        locale.setlocale(locale.LC_ALL, "")
    except locale.Error:
        os.environ['LC_ALL'] = 'C'
        locale.setlocale(locale.LC_ALL, "")

    gettext.bindtextdomain(GETTEXT_PROGNAME, '/usr/share/locale')
    gettext.textdomain(GETTEXT_PROGNAME)

    CMDARGS = ArgumentParser(description = _('Smartly runs analyze events'))
    CMDARGS.add_argument('-d', '--problem-dir', type=str,
                         default='.', help=_('Problem directory'))

    OPTIONS = CMDARGS.parse_args()

    sys.exit(run_analyze_smart(vars(OPTIONS)['problem_dir']))
